#include "connetwork.h"

namespace connetwork{

void work::createSocket()
{
    if((sever_fd = socket(AF_INET,SOCK_STREAM,0)) == 0)
    {
        work::logermanager->log(loger::LogLevel::INFO,"Socket creation failed");
        // printf("Socket creation failed");
        exit(EXIT_FAILURE);
    }
    work::logermanager->log(loger::LogLevel::INFO,"Socket created sucessfully");
    // cout<<"Socket created sucessfully"<<endl;
}
void work::bindSocket()
{
      struct sockaddr_in address;
        int opt = 1;

        if (setsockopt(sever_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
            logermanager->log(loger::LogLevel::ERROR,"Setsockopt failed");
            // perror("Setsockopt failed");
            close(sever_fd);
            exit(EXIT_FAILURE);
        }

        address.sin_family = AF_INET;
        address.sin_addr.s_addr = INADDR_ANY;
        address.sin_port = htons(sever_port);

        if (bind(sever_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
            logermanager->log(loger::LogLevel::ERROR,"Bind failed");
            // perror("Bind failed");
            close(sever_fd);
            exit(EXIT_FAILURE);
        }
   

        string logmessg = "Socket bound to port " + to_string(sever_port)+  "." ;
        logermanager->log(loger::LogLevel::INFO,logmessg);
        // cout << "Socket bound to port " << sever_port << "." << std::endl;
}

void work::listenForConnections() {
    if (listen(sever_fd, 3) < 0) {
        logermanager->log(loger::LogLevel::ERROR,"Listen failed");
        // perror("Listen failed");
        close(sever_fd);
        exit(EXIT_FAILURE);
    }
    string messge = "Server is listening on port " + to_string(sever_port)+" . ";
    // std::cout << "Server is listening on port " << sever_port << "." << std::endl;
     logermanager->log(loger::LogLevel::INFO,messge);
    while (true) {
        int new_socket = accept(sever_fd, (struct sockaddr *)&client_address, &client_len);

        if (new_socket < 0) {
            // perror("Accept failed");
            logermanager->log(loger::LogLevel::ERROR,"Accept failed");
            continue;
        }

        // std::cout << "New client connected!" << std::endl;
        logermanager->log(loger::LogLevel::INFO,"New client connected!");
        // 在这里启动接收和发送消息的线程
        std::thread receiver(&work::receiveMessages, this, new_socket);
        std::thread sender(&work::sendMessages, this, new_socket);

        // 分离线程，让它们独立运行
        receiver.detach();
        sender.detach();
    }
}


void work::receiveMessages(int client_socket) {
    char buffer[BUFFER_SIZE] = {0};
    while (true) {
        memset(buffer, 0, BUFFER_SIZE);
        int bytes_received = recv(client_socket, buffer, BUFFER_SIZE - 1, 0);
        if (bytes_received <= 0) {
            logermanager->log(loger::LogLevel::ERROR,"Client disconnected or error occurred.");
            // std::cout << "Client disconnected or error occurred." << std::endl;
            break;
        }
        string buffer_s = buffer;
        string messge = "Received from client: " + buffer_s;
        logermanager->log(loger::LogLevel::INFO,messge);
        // std::cout << "Received from client: " << buffer << std::endl;
    }
    close(client_socket); // 关闭客户端套接字
}

void work::sendMessages(int client_socket) {
    std::string message;

    while (true) {
        logermanager->log(loger::LogLevel::INFO,"Enter message to send to client: ");
        // std::cout << "Enter message to send to client: ";
        std::getline(std::cin, message);

        if (message.empty()) {
            logermanager->log(loger::LogLevel::ERROR, "Empty message. Please enter a valid message.");
            // std::cerr << "Empty message. Please enter a valid message." << std::endl;
            continue;
        }

        ssize_t bytesSent = send(client_socket, message.c_str(), message.size(), 0);
        if (bytesSent < 0) {
            logermanager->log(loger::LogLevel::ERROR, "Failed to send message to client");
            // perror("Failed to send message to client");
            break;
        } else {
            // string buff = bytesSent;
            string seeseg =  "Message sent successfully ("+ to_string(bytesSent)+ " bytes).";
            logermanager->log(loger::LogLevel::INFO, seeseg);
            // std::cout << "Message sent successfully (" << bytesSent << " bytes)." << std::endl;
        }
    }
    close(client_socket); // 关闭客户端套接字
}


/******************************TCPServer*************************************** */
TCPServer::TCPServer()
{
    workfd = new work;
    workfd->logermanager->log(loger::LogLevel::INFO,"TCPServer init successfully");
    // cout<<"TCPServer init successfully"<<endl;
}
TCPServer::~TCPServer()
{
    if(workfd != nullptr)
    {
        delete workfd;
    }
}
void TCPServer::run() 
{
    workfd->createSocket();
    workfd->bindSocket();
    workfd->listenForConnections();
}
}